package file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class DirDemo {
    static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {

        System.out.println("请输入要扫描的目录:");
        String rootPath = scanner.nextLine();

        File rootFile = new File(rootPath);
        if (!rootFile.isDirectory()){
            System.out.println("请输入正确的目录!!");
            return;
        }

        System.out.println("请输入要删除的文件名关键字:");
        String toDeleteKey = scanner.nextLine();

        //查找所有相关的文件
        List<File> toDeleteFiles = new ArrayList<>();
        scanDir(rootFile,toDeleteKey,toDeleteFiles);
        //询问用户是否删除
        confirmDelete(toDeleteFiles);

    }

    private static void confirmDelete(List<File> toDeleteFiles) {
        if (toDeleteFiles.size() == 0){
            return;
        }
        for (File file: toDeleteFiles){
            System.out.println("是否删除文件:"+ file.getPath());
            String deleteFlag = scanner.nextLine();
            //equal  方法使用时, 要把常量放在前面
            //如果deleteFlag==null
            // "y".equals(deleteFlag) 不会有空指针异常
            //deleteFlag.equals("y")  会有空指针异常
            if ("y".equals(deleteFlag)){
                System.out.println("即将删除文件:"+file.getPath());
                file.delete();
            }
        }
    }

    private static void scanDir(File rootFile, String toDeleteKey, List<File> toDeleteFiles) {
        File[] files = rootFile.listFiles();
        if (files == null || files.length ==0){
            return;
        }
        //如果不为空, 则依次遍历他的子目录
        for (File f: files){
            if (f.isDirectory()){
                scanDir(f,toDeleteKey,toDeleteFiles);
            }else {
                if (f.isFile() && f.getName().contains(toDeleteKey)){
                    toDeleteFiles.add(f);
                }
            }
        }
    }
}
